import _ from "lodash";
export type EnumItem = {
    label: string;
    value: string | number;
    type: string;
    group?: string;
    children?: EnumItem[];
};


type EnumData = {
    [key: string]: EnumItem[];
};

// 使用对象字面量定义EnumManager
export const enums = {
    enumData: {} as EnumData,

    append(data: any, parentType?: string, pvalue?: string) {
        if (Array.isArray(data)) {
            data.forEach((item: any) => this.append(item, parentType, pvalue));
        } else if (typeof data === 'object' && data !== null) {
            let { label, value, type: itemType, children, group } = data;
            itemType = (itemType ? _.kebabCase(itemType) : pvalue) || '';
            parentType = parentType || '';
            group = _.kebabCase(group || '');
            const finalType = _.kebabCase(`${parentType}-${itemType}`);

            if (label && value) {
                const enumItem: EnumItem = {
                    label, value, group, type: finalType, children: children || []
                };

                if (!this.enumData[finalType]) {
                    this.enumData[finalType] = [];
                }
                this.enumData[finalType].push(enumItem);

                if (children && Array.isArray(children)) {
                    this.append(children, finalType, value);
                }
            }
        }
    },

    getAll(): EnumData {
        return this.enumData;
    },

    getName(type: string, value: string | number, def: string = "-"): string {
        const items = this.enumData[_.kebabCase(type)];
        if (items) {
            const item = items.find((item: EnumItem) => item.value === value);
            return item ? item.label : def;
        }
        return def;
    },

    getChildren(type: string, value: string | number): EnumItem[] {
        const items = this.enumData[_.kebabCase(type)];
        let _value = String(value).toLowerCase();
        if (items) {
            const item = items.find((item: EnumItem) => String(item.value).toLowerCase() === _value);
            return item ? item.children || [] : [];
        }
        return [];
    },

    getItems(type: string, group?: string): EnumItem[] {
        const kebabCasedType = this.joinType(type);
        let items = this.enumData[kebabCasedType] || [];
        let _group = this.joinType(group || "");
        if (_group) {
            items = items.filter(item => item.group === _group);
        }
        return items;
    },

    joinType(...types: string[]): string {
        return _.kebabCase(types.join('-'));
    },
    getValueChar(value: string): string {
        const match = value.match(/^[A-Za-z]+/);
        return match ? match[0] : "";
    }


    // 注意：这里没有构造函数，因为我们已经是一个对象实例了
};

